package tech.summerly.weather.data.local

import android.arch.persistence.db.SupportSQLiteDatabase
import android.arch.persistence.room.Database
import android.arch.persistence.room.Room
import android.arch.persistence.room.RoomDatabase
import kotlinx.coroutines.experimental.async
import tech.summerly.weather.AppContext
import tech.summerly.weather.model.Region
import tech.summerly.weather.model.UserRegion

@Database(entities = [Region::class, UserRegion::class], version = 2, exportSchema = false)
abstract class RegionDataBase : RoomDatabase() {


    abstract fun userRegionDao(): UserRegionDao

    abstract fun regionDao(): RegionDao

    companion object {

        private const val DB_CHINA = "region.db"

        val INSTANCE: RegionDataBase by lazy {
            Room.databaseBuilder(AppContext.instance, RegionDataBase::class.java, DB_CHINA)
                    .addCallback(object : Callback() {
                        override fun onCreate(db: SupportSQLiteDatabase) {
                            //将所有json数据转移到数据库中去
                            async { RegionJsonReader().readRegionJson2Db() }
                        }
                    })
                    .allowMainThreadQueries()
                    .build()
        }
    }

}